<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="root">
        <h1>Hello</h1>
        <Cmp1></Cmp1>
        <UserLogin></UserLogin>
    </div>

    <script>
    function render(options){
        let root = null;
        if(typeof options.root == 'string'){
            // querySelector只能选择第一个匹配的节点
            root = document.querySelector(options.root);
            if(!root){
                throw new Error(`${options.root} 找不到`);
            }
        }else if(options.root instanceof HTMLElement){// 判断类型 options.root.constructor.__proto__
            root = options.root;
        }else{
            throw new Error(`root 不存在`);
        }
        console.log(root);

        let elements = root.getElementsByTagName('*');
        Array.from(elements).forEach(element=>{
            if(element.constructor == HTMLUnknownElement){// 判断 element.constructor
                // console.log(element.tagName);
                for(let index in options.components) {// 用for in的方遍历数组
                    if(index.toLowerCase() == element.tagName.toLowerCase()){
                        let cmp = new options.components[index];// 获取 array[index]
                        let res = cmp.render();
                        element.parentNode.replaceChild(res,element);// 替换内容
                    }
                };
            }
        })
    }

    // 抽象类
    class Component{
        render(){
            throw new Error(`render 方法未定义`);
        }
    }

    class Cmp1 extends Component{
        render(){
            let div = document.createElement('div');
            div.innerHTML = 'This is Cmp1!';
            return div;
        }
    }

    class UserLogin extends Component{
        render(){
            let div = document.createElement('div');
            div.innerHTML = 'This is UserLogin!';
            return div;
        }
    }

    render({
        // root:document.getElementById('root1')
        root:'#root',
        components:{
            Cmp1,UserLogin
        }
    });
    
    </script>
</body>
</html>